/*
 * ExpressOlympView.java
 */

package ru.ipo.dces.editors.expressolymp;

import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;

import javax.swing.*;
import javax.swing.table.*;
import java.util.Enumeration;
import java.util.Vector;
import java.io.*;
import java.net.URL;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import java.util.Random;

import ru.ipo.dces.utils.ZipUtils;

/**
 * The application's main frame.
 */
public class ExpressOlympView extends FrameView {

    public ExpressOlympView(SingleFrameApplication app) {
        super(app);

        initComponents();

        TablePred.setModel(TableMod);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ExpressOlympApp.getApplication().getMainFrame();
            aboutBox = new ExpressOlympAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ExpressOlympApp.getApplication().show(aboutBox);
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings({"unchecked", "RedundantArrayCreation"})
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        NewPred = new javax.swing.JTextField();
        AddNewPred = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        PredList = new javax.swing.JList(PredlistModel);
        EditTableText = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TablePred = new javax.swing.JTable();
        Minus = new javax.swing.JButton();
        Plus = new javax.swing.JButton();
        Sharp = new javax.swing.JButton();
        Question = new javax.swing.JButton();
        ClearTable = new javax.swing.JButton();
        EditPredText = new javax.swing.JLabel();
        ChangePred = new javax.swing.JButton();
        DelPred = new javax.swing.JButton();
        PredEdit = new javax.swing.JTextField();
        SaveEditPred = new javax.swing.JButton();
        CancelEditPred = new javax.swing.JButton();
        addImg = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        jComboBox1 = new javax.swing.JComboBox();

        mainPanel.setName("mainPanel"); // NOI18N
        EditTableText.setEnabled(false);
        Plus.setEnabled(false);
        Minus.setEnabled(false);
        Question.setEnabled(false);
        Sharp.setEnabled(false);
        ClearTable.setEnabled(false);
        EditPredText.setEnabled(false);
        PredEdit.setEnabled(false);
        ChangePred.setEnabled(false);
        DelPred.setEnabled(false);
        SaveEditPred.setEnabled(false);
        CancelEditPred.setEnabled(false);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympView.class);
        NewPred.setText(resourceMap.getString("addPred.text")); // NOI18N
        NewPred.setName("addPred"); // NOI18N
        NewPred.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                NewPredFocusGained(evt);
            }

            public void focusLost(java.awt.event.FocusEvent evt) {
                NewPredFocusLost(evt);
            }
        });

        AddNewPred.setFont(resourceMap.getFont("Add.font")); // NOI18N
        AddNewPred.setText(resourceMap.getString("Add.text")); // NOI18N
        AddNewPred.setName("Add"); // NOI18N
        AddNewPred.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AddNewPredMouseClicked(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        PredList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        PredList.setName("PredList"); // NOI18N
        PredList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                PredListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(PredList);

        EditTableText.setFont(resourceMap.getFont("EditTableText.font")); // NOI18N
        EditTableText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        EditTableText.setText(resourceMap.getString("EditTableText.text")); // NOI18N
        EditTableText.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        EditTableText.setInheritsPopupMenu(false);
        EditTableText.setName("EditTableText"); // NOI18N
        EditTableText.setRequestFocusEnabled(false);
        EditTableText.setVerifyInputWhenFocusTarget(false);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        TablePred.setBackground(resourceMap.getColor("TablePred.background")); // NOI18N
        TablePred.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        TablePred.setColumnSelectionAllowed(true);
        TablePred.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        TablePred.setGridColor(resourceMap.getColor("TablePred.gridColor")); // NOI18N
        TablePred.setInheritsPopupMenu(true);
        TablePred.setName("TablePred"); // NOI18N
        TablePred.setUpdateSelectionOnSort(false);
        TablePred.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                TablePredFocusGained(evt);
            }
        });
        jScrollPane2.setViewportView(TablePred);

        Minus.setText(resourceMap.getString("Minus.text")); // NOI18N
        Minus.setMaximumSize(new java.awt.Dimension(25, 30));
        Minus.setMinimumSize(new java.awt.Dimension(25, 30));
        Minus.setName("Minus"); // NOI18N
        Minus.setPreferredSize(new java.awt.Dimension(25, 30));
        Minus.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MinusMouseClicked(evt);
            }
        });

        Plus.setText(resourceMap.getString("plus.text")); // NOI18N
        Plus.setMaximumSize(new java.awt.Dimension(25, 30));
        Plus.setMinimumSize(new java.awt.Dimension(25, 30));
        Plus.setName("plus"); // NOI18N
        Plus.setPreferredSize(new java.awt.Dimension(25, 30));
        Plus.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                PlusMouseClicked(evt);
            }
        });

        Sharp.setText(resourceMap.getString("sharp.text")); // NOI18N
        Sharp.setMaximumSize(new java.awt.Dimension(25, 30));
        Sharp.setMinimumSize(new java.awt.Dimension(25, 30));
        Sharp.setName("sharp"); // NOI18N
        Sharp.setPreferredSize(new java.awt.Dimension(25, 30));
        Sharp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SharpMouseClicked(evt);
            }
        });

        Question.setText(resourceMap.getString("question.text")); // NOI18N
        Question.setMaximumSize(new java.awt.Dimension(25, 30));
        Question.setMinimumSize(new java.awt.Dimension(25, 30));
        Question.setName("question"); // NOI18N
        Question.setPreferredSize(new java.awt.Dimension(25, 30));
        Question.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                QuestionMouseClicked(evt);
            }
        });

        ClearTable.setText(resourceMap.getString("clear.text")); // NOI18N
        ClearTable.setName("clear"); // NOI18N
        ClearTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ClearTableMouseClicked(evt);
            }
        });

        EditPredText.setFont(resourceMap.getFont("EditPredText.font")); // NOI18N
        EditPredText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        EditPredText.setText(resourceMap.getString("EditPredText.text")); // NOI18N
        EditPredText.setName("EditPredText"); // NOI18N

        ChangePred.setText(resourceMap.getString("ChangePred.text")); // NOI18N
        ChangePred.setName("ChangePred"); // NOI18N
        ChangePred.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ChangePredMouseClicked(evt);
            }
        });

        DelPred.setText(resourceMap.getString("DelPred.text")); // NOI18N
        DelPred.setName("DelPred"); // NOI18N
        DelPred.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                DelPredMouseClicked(evt);
            }
        });

        PredEdit.setEditable(false);
        PredEdit.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        PredEdit.setText(resourceMap.getString("PredEdit.text")); // NOI18N
        PredEdit.setName("PredEdit"); // NOI18N

        SaveEditPred.setText(resourceMap.getString("SaveEditPred.text")); // NOI18N
        SaveEditPred.setName("SaveEditPred"); // NOI18N
        SaveEditPred.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SaveEditPredMouseClicked(evt);
            }
        });

        CancelEditPred.setText(resourceMap.getString("CancelEditPred.text")); // NOI18N
        CancelEditPred.setName("CancelEditPred"); // NOI18N
        CancelEditPred.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CancelEditPredMouseClicked(evt);
            }
        });

        addImg.setText(resourceMap.getString("addImg.text")); // NOI18N
        addImg.setName("addImg"); // NOI18N
        addImg.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addImgMouseClicked(evt);
            }
        });

        jLabel1.setIcon(resourceMap.getIcon("jLabel1.icon")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addGap(63, 63, 63)
                                                .addComponent(Plus, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(Minus, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(Question, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(Sharp, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(ClearTable)
                                                .addGap(212, 212, 212))
                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addComponent(ChangePred, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addComponent(SaveEditPred, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
                                                                .addGap(171, 171, 171)
                                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addComponent(DelPred, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                        .addComponent(CancelEditPred, javax.swing.GroupLayout.Alignment.TRAILING)))
                                                        .addComponent(addImg)
                                                        .addComponent(NewPred, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                                                        .addComponent(EditPredText, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                                                        .addComponent(PredEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE)
                                                        .addComponent(EditTableText, javax.swing.GroupLayout.DEFAULT_SIZE, 385, Short.MAX_VALUE))
                                                .addGap(18, 18, 18)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                                .addComponent(AddNewPred, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
                                                                .addGap(10, 10, 10))
                                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(12, 12, 12))
        );

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{EditPredText, NewPred, PredEdit, jScrollPane1});

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{CancelEditPred, ChangePred, DelPred, SaveEditPred});

        mainPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{Minus, Plus, Question, Sharp});

        mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                        .addComponent(AddNewPred, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                                                                .addComponent(NewPred, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                .addGap(11, 11, 11)
                                                                .addComponent(addImg)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGap(18, 18, 18)
                                                .addComponent(EditPredText)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(PredEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                                .addComponent(ChangePred)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(SaveEditPred))
                                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                                .addComponent(DelPred)
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addComponent(CancelEditPred)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(EditTableText, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                                                        .addComponent(Question, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(Sharp, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(Plus, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(Minus, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(ClearTable))))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        mainPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[]{CancelEditPred, ChangePred, DelPred, SaveEditPred});

        mainPanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[]{ClearTable, Minus, Plus, Question, Sharp});

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getActionMap(ExpressOlympView.class, this);
        jMenuItem3.setAction(actionMap.get("newfile")); // NOI18N
        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        fileMenu.add(jMenuItem3);

        jMenuItem2.setAction(actionMap.get("openAs")); // NOI18N
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        fileMenu.add(jMenuItem2);

        jMenuItem1.setAction(actionMap.get("saveAs")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        jMenuItem4.setAction(actionMap.get("generateTask")); // NOI18N
        jMenuItem4.setText(resourceMap.getString("jMenuItem4.text")); // NOI18N
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        fileMenu.add(jMenuItem4);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));
        jComboBox1.setName("jComboBox1"); // NOI18N

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void NewPredFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_NewPredFocusLost
        if (NewPred.getText().equals(""))
            NewPred.setText("Введите предикат");
    }//GEN-LAST:event_NewPredFocusLost

    private void AddNewPredMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AddNewPredMouseClicked
        if (NewPred.getText().equals("") || NewPred.getText().equals("Введите предикат"))
            javax.swing.JOptionPane.showMessageDialog(null, "Вы ничего не ввели");
        else {
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympApp.class);
            predicates.add(new Predicate(NewPred.getText(), resourceMap.getImageIcon("NoImage.icon")));

            PredlistModel.addElement((char) ('A' + PredlistModel.getSize()) + " = " + NewPred.getText());
            NewPred.setText("Введите предикат");

            //table
            if (TableMod.getColumnCount() == 0)
                TableMod.addColumn("");
            TableMod.addColumn((char) ('A' + PredlistModel.getSize() - 1));
            Vector<String> s = new Vector<String>();
            s.add((char) ('A' + PredlistModel.getSize() - 1) + "");
            TableMod.addRow(s);
            TableMod.setValueAt("#", PredlistModel.getSize() - 1, PredlistModel.getSize());

            setColumnNoEdit(TablePred, 0);

            //Потеря выделения таблицы. Убираем кнопки
            EditTableText.setEnabled(false);
            Plus.setEnabled(false);
            Minus.setEnabled(false);
            Question.setEnabled(false);
            Sharp.setEnabled(false);
            ClearTable.setEnabled(false);
        }
    }//GEN-LAST:event_AddNewPredMouseClicked

    private void ChangePredMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ChangePredMouseClicked
        if (!predicates.get(PredList.getSelectedIndex()).name.equals("См. рисунок")) {
            PredEdit.setEditable(true);
            SaveEditPred.setEnabled(true);
            CancelEditPred.setEnabled(true);
            ChangePred.setEnabled(false);
            DelPred.setEnabled(false);
            PredEdit.requestFocus();

            NewPred.setEnabled(false);
            addImg.setEnabled(false);
            AddNewPred.setEnabled(false);
            PredList.setEnabled(false);
            jLabel1.setEnabled(false);
            TablePred.setEnabled(false);
            EditTableText.setEnabled(false);
            Plus.setEnabled(false);
            Minus.setEnabled(false);
            Question.setEnabled(false);
            Sharp.setEnabled(false);
            ClearTable.setEnabled(false);
        } else {
            try {
                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new File("."));
                String[] ext = {"jpg", "png", "gif"};
                ExtFileFilter textFileFilter = new ExtFileFilter(ext);
                //Отключение вывода расширения в строке описания, так как расширение уже задано в строке описания
                textFileFilter.setExtensionListInDescription(false);
                chooser.addChoosableFileFilter(textFileFilter);
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {

                    URL imgURL = chooser.getSelectedFile().toURI().toURL();
                    ImageIcon icon = new ImageIcon(imgURL);

                    Image newimg = icon.getImage().getScaledInstance(127, 127, java.awt.Image.SCALE_SMOOTH);
                    jLabel1.setIcon(new ImageIcon(newimg));

                    newimg = icon.getImage().getScaledInstance(640, 640, java.awt.Image.SCALE_SMOOTH);
                    predicates.get(PredList.getSelectedIndex()).image = new ImageIcon(newimg);

                }
            } catch (NumberFormatException e) {
                System.out.println("Number Format Exception");
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }//GEN-LAST:event_ChangePredMouseClicked

    private void CancelEditPredMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CancelEditPredMouseClicked
        PredEdit.setEditable(false);
        PredEdit.setText(((String) PredList.getSelectedValue()).substring(4));
        SaveEditPred.setEnabled(false);
        CancelEditPred.setEnabled(false);
        ChangePred.setEnabled(true);
        DelPred.setEnabled(true);

        NewPred.setEnabled(true);
        addImg.setEnabled(true);
        AddNewPred.setEnabled(true);
        PredList.setEnabled(true);
        jLabel1.setEnabled(true);
        TablePred.setEnabled(true);
        if (TablePred.getSelectedColumn() > 0) {
            EditTableText.setEnabled(true);
            Plus.setEnabled(true);
            Minus.setEnabled(true);
            Question.setEnabled(true);
            Sharp.setEnabled(true);
            ClearTable.setEnabled(true);
        }
    }//GEN-LAST:event_CancelEditPredMouseClicked

    private void SaveEditPredMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveEditPredMouseClicked
        PredlistModel.setElementAt((String) ((char) ('A' + PredList.getSelectedIndex()) + " = " + PredEdit.getText()), PredList.getSelectedIndex());
        predicates.get(PredList.getSelectedIndex()).name = PredEdit.getText();
        PredEdit.setEditable(false);
        SaveEditPred.setEnabled(false);
        CancelEditPred.setEnabled(false);
        ChangePred.setEnabled(true);
        DelPred.setEnabled(true);

        NewPred.setEnabled(true);
        addImg.setEnabled(true);
        AddNewPred.setEnabled(true);
        PredList.setEnabled(true);
        jLabel1.setEnabled(true);
        if (TablePred.getSelectedColumn() > 0) {
            TablePred.setEnabled(true);
            EditTableText.setEnabled(true);
            Plus.setEnabled(true);
            Minus.setEnabled(true);
            Question.setEnabled(true);
            Sharp.setEnabled(true);
            ClearTable.setEnabled(true);
        }
    }//GEN-LAST:event_SaveEditPredMouseClicked

    private void NewPredFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_NewPredFocusGained
        if (NewPred.getText().equals("Введите предикат"))
            NewPred.setText("");
    }//GEN-LAST:event_NewPredFocusGained

    private void DelPredMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DelPredMouseClicked
        int i = PredList.getSelectedIndex();
        String s, s2;
        //Table edit
        TableMod.removeRow(i);
        removeColumnAndData(TablePred, i + 1);

        predicates.removeElementAt(i);
        PredlistModel.removeElementAt(i);

        for (; i < PredlistModel.getSize(); i++) {
            s = (String) PredlistModel.getElementAt(i);
            s2 = (char) ('A' + i) + s.substring(1);
            PredlistModel.setElementAt(s2, i);

            TableMod.setValueAt((char) ('A' + i), i, 0);
        }

        setColumnNoEdit(TablePred, 0);

        PredEdit.setEditable(false);
        PredEdit.setEnabled(false);
        PredEdit.setText("");
        ChangePred.setEnabled(false);
        DelPred.setEnabled(false);
        EditPredText.setEnabled(false);

        //Потеря выделения таблицы. Убираем кнопки
        EditTableText.setEnabled(false);
        Plus.setEnabled(false);
        Minus.setEnabled(false);
        Question.setEnabled(false);
        Sharp.setEnabled(false);
        ClearTable.setEnabled(false);
    }//GEN-LAST:event_DelPredMouseClicked

    private void TablePredFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TablePredFocusGained
        if (TablePred.getSelectedColumn() != 0) {
            EditTableText.setEnabled(true);
            Plus.setEnabled(true);
            Minus.setEnabled(true);
            Question.setEnabled(true);
            Sharp.setEnabled(true);
            ClearTable.setEnabled(true);
        }
    }//GEN-LAST:event_TablePredFocusGained

    private void PlusMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_PlusMouseClicked
        if (TablePred.getSelectedColumn() != 0)
            TableMod.setValueAt("+", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
    }//GEN-LAST:event_PlusMouseClicked

    private void MinusMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MinusMouseClicked
        if (TablePred.getSelectedColumn() != 0)
            TableMod.setValueAt("-", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
    }//GEN-LAST:event_MinusMouseClicked

    private void QuestionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_QuestionMouseClicked
        if (TablePred.getSelectedColumn() != 0)
            TableMod.setValueAt("?", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
    }//GEN-LAST:event_QuestionMouseClicked

    private void SharpMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SharpMouseClicked
        if (TablePred.getSelectedColumn() != 0)
            TableMod.setValueAt("#", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
    }//GEN-LAST:event_SharpMouseClicked

    private void ClearTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ClearTableMouseClicked
        if (TablePred.getSelectedColumn() != 0)
            if (TablePred.getSelectedColumn() - 1 == TablePred.getSelectedRow())
                TableMod.setValueAt("#", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
            else
                TableMod.setValueAt("", TablePred.getSelectedRow(), TablePred.getSelectedColumn());
    }//GEN-LAST:event_ClearTableMouseClicked

    private void addImgMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addImgMouseClicked
        try {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("."));
            String[] ext = {"jpg", "png", "gif"};
            ExtFileFilter textFileFilter = new ExtFileFilter(ext);
            //Отключение вывода расширения в строке описания, так как расширение уже задано в строке описания
            textFileFilter.setExtensionListInDescription(false);
            chooser.addChoosableFileFilter(textFileFilter);
            if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                //---

                URL imgURL = chooser.getSelectedFile().toURI().toURL();
                ImageIcon icon = new ImageIcon(imgURL);

                predicates.add(new Predicate("См. рисунок", icon));

                Image newimg = icon.getImage().getScaledInstance(127, 127, java.awt.Image.SCALE_SMOOTH);
                jLabel1.setIcon(new ImageIcon(newimg));

                PredlistModel.addElement((char) ('A' + PredlistModel.getSize()) + " = См. рисунок");
                NewPred.setText("Введите предикат");

                //table
                if (TableMod.getColumnCount() == 0)
                    TableMod.addColumn("");
                TableMod.addColumn((char) ('A' + PredlistModel.getSize() - 1));
                Vector<String> s = new Vector<String>();
                s.add((char) ('A' + PredlistModel.getSize() - 1) + "");
                TableMod.addRow(s);
                TableMod.setValueAt("#", PredlistModel.getSize() - 1, PredlistModel.getSize());

                setColumnNoEdit(TablePred, 0);

                //Потеря выделения таблицы. Убираем кнопки
                EditTableText.setEnabled(false);
                Plus.setEnabled(false);
                Minus.setEnabled(false);
                Question.setEnabled(false);
                Sharp.setEnabled(false);
                ClearTable.setEnabled(false);
            }
        } catch (NumberFormatException e) {
            System.out.println("Number Format Exception");
            return;
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }//GEN-LAST:event_addImgMouseClicked

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
        if (PredList.getSelectedIndex() != -1) {
            PicJFrame pf = new PicJFrame(predicates.get(PredList.getSelectedIndex()));
            pf.setVisible(true);
        }
    }//GEN-LAST:event_jLabel1MouseClicked

    private void PredListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_PredListValueChanged
        if (PredList.getSelectedIndex() != -1) {
            EditPredText.setEnabled(true);
            PredEdit.setText(predicates.get(PredList.getSelectedIndex()).name);

            if (predicates.get(PredList.getSelectedIndex()).name.equals("См. рисунок")) {
                Image newimg = predicates.get(PredList.getSelectedIndex()).image.getImage().getScaledInstance(127, 127, java.awt.Image.SCALE_SMOOTH);
                jLabel1.setIcon(new ImageIcon(newimg));
            } else {
                org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympApp.class);
                jLabel1.setIcon(resourceMap.getImageIcon("NoImageIcon.icon"));
            }

            PredEdit.setEnabled(true);
            ChangePred.setEnabled(true);
            DelPred.setEnabled(true);
        }
    }//GEN-LAST:event_PredListValueChanged


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddNewPred;
    private javax.swing.JButton CancelEditPred;
    private javax.swing.JButton ChangePred;
    private javax.swing.JButton ClearTable;
    private javax.swing.JButton DelPred;
    private javax.swing.JLabel EditPredText;
    private javax.swing.JLabel EditTableText;
    private javax.swing.JButton Minus;
    private javax.swing.JTextField NewPred;
    private javax.swing.JButton Plus;
    private javax.swing.JTextField PredEdit;
    private javax.swing.JList PredList;
    private javax.swing.JButton Question;
    private javax.swing.JButton SaveEditPred;
    private javax.swing.JButton Sharp;
    private javax.swing.JTable TablePred;
    private javax.swing.JButton addImg;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables

    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private DefaultListModel PredlistModel = new DefaultListModel();
    private DefaultTableModel TableMod = new MyDefaultTableModel();

    private Vector<Predicate> predicates = new Vector();

    private JDialog aboutBox;

    // This subclass adds a method to retrieve the columnIdentifiers
    // which is needed to implement the removal of
    // column data from the table model
    class MyDefaultTableModel extends DefaultTableModel {

        public Vector getColumnIdentifiers() {
            return columnIdentifiers;
        }
    }

    public void removeColumnAndData(JTable table, int vColIndex) {
        MyDefaultTableModel model = (MyDefaultTableModel) table.getModel();
        TableColumn col = table.getColumnModel().getColumn(vColIndex);
        int columnModelIndex = col.getModelIndex();
        Vector data = model.getDataVector();
        Vector colIds = model.getColumnIdentifiers();

        // Remove the column from the table
        table.removeColumn(col);

        // Remove the column header from the table model
        for (int i = data.size(); i >= vColIndex; i--) {
            System.out.println(colIds.get(i));
            colIds.setElementAt(colIds.get(i), i + 1);
        }

        colIds.removeElementAt(columnModelIndex);

        // Remove the column data
        for (int r = 0; r < data.size(); r++) {
            Vector row = (Vector) data.get(r);
            row.removeElementAt(columnModelIndex);
        }
        model.setDataVector(data, colIds);

        // Correct the model indices in the TableColumn objects
        // by decrementing those indices that follow the deleted column
        Enumeration enum1 = table.getColumnModel().getColumns();
        for (; enum1.hasMoreElements();) {
            TableColumn c = (TableColumn) enum1.nextElement();
            if (c.getModelIndex() >= columnModelIndex) {
                c.setModelIndex(c.getModelIndex() - 1);
            }
        }
        model.fireTableStructureChanged();
    }

    //Делаем 1 столбец нередактируемым
    public void setColumnNoEdit(JTable table, int col) {
        table.getColumnModel().getColumn(col).setCellEditor(new javax.swing.table.TableCellEditor() {
            @Override
            public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
                return null;
            }

            @Override
            public Object getCellEditorValue() {
                return null;
            }

            @Override
            public boolean isCellEditable(java.util.EventObject anEvent) {
                return false;
            }

            @Override
            public boolean shouldSelectCell(java.util.EventObject anEvent) {
                return false;
            }

            @Override
            public boolean stopCellEditing() {
                return false;
            }

            @Override
            public void cancelCellEditing() {
            }

            @Override
            public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
            }

            @Override
            public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
            }
        });

        //цвет
        DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
        defaultTableCellRenderer.setBackground(table.getTableHeader().getBackground());
        table.getColumnModel().getColumn(col).setCellRenderer(defaultTableCellRenderer);
    }

    @Action
    public void saveAs() {
        try {
            //check
            if (TablePred.getRowCount() < 6) {
                javax.swing.JOptionPane.showMessageDialog(null, "Для успешной генерации тестов число предикатов должно быть не меньше 6");
                return;
            }
            for (int j = 0; j < TablePred.getRowCount(); j++)
                for (int i = 1; i < TablePred.getColumnCount(); i++) {
                    if (TableMod.getValueAt(j, i) == null || TableMod.getValueAt(j, i).toString().equals("")) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Незаполненное поле [" + (char) ('A' + j) + " ," + (char) ('A' + i - 1) + "]");
                        return;
                    }
                    if (!(TableMod.getValueAt(j, i).toString().equals("+") || TableMod.getValueAt(j, i).toString().equals("-") || TableMod.getValueAt(j, i).toString().equals("?") || TableMod.getValueAt(j, i).toString().equals("#"))) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Недопустимое значение в поле [" + (char) ('A' + j) + " ," + (char) ('A' + i - 1) + "]");
                        return;
                    }
                }

            String fstr = "task.eo";
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("."));
            ExtFileFilter textFileFilter = new ExtFileFilter("eo", "Задачи экспресс-олимпиады (*.eo)");
            //Отключение вывода расширения в строке описания, так как расширение уже задано в строке описания
            textFileFilter.setExtensionListInDescription(false);
            chooser.addChoosableFileFilter(textFileFilter);

            if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                String path = chooser.getSelectedFile().getPath();
                if (path.endsWith(".eo"))
                    fstr = path;
                else
                    fstr = path + ".eo";

                Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fstr), "UTF8"));
                fw.write("Predicates start\n");
                for (int i = 0; i < PredlistModel.size(); i++) {
                    fw.write(predicates.get(i).name + "\n");
                    if (predicates.get(i).name.equals("См. рисунок")) {
                        Image img = predicates.get(i).image.getImage();
                        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
                        Graphics2D g2 = bi.createGraphics();
                        g2.drawImage(img, 0, 0, null);
                        g2.dispose();

                        if (path.contains("\\")) {    //windows
                            System.out.println("WINDOWS");
                            path = path.substring(0, path.lastIndexOf('\\') + 1);
                        }
                        if (path.contains("/")) {  //unix
                            System.out.println("UNIX");
                            path = path.substring(0, path.lastIndexOf('/') + 1);
                        }

                        ImageIO.write(bi, "jpg", new File(path + chooser.getSelectedFile().getName() + i + ".jpg"));
                    }
                }
                fw.write("Predicates end\n");
                fw.write("Table start\n");
                for (int j = 0; j < TablePred.getRowCount(); j++) {
                    for (int i = 1; i < TablePred.getColumnCount(); i++)
                        fw.write(TableMod.getValueAt(j, i).toString());
                    fw.write("\n");
                }
                fw.write("Table end");
                fw.close();
                javax.swing.JOptionPane.showMessageDialog(null, "Файл успешно сохранен");
            }
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            return;
        } catch (NumberFormatException e) {
            System.out.println("Number Format Exception");
            return;
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }

    @Action
    public void openAs() {
        try {
            String fstr;
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("."));
            ExtFileFilter textFileFilter = new ExtFileFilter("eo", "Задачи экспресс-олимпиады (*.eo)");
            //Отключение вывода расширения в строке описания, так как расширение уже задано в строке описания
            textFileFilter.setExtensionListInDescription(false);
            chooser.addChoosableFileFilter(textFileFilter);
            if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                fstr = chooser.getSelectedFile().getAbsolutePath();

                Reader fr = new BufferedReader(new InputStreamReader(new FileInputStream(fstr), "UTF8"));
                BufferedReader br = new BufferedReader(fr);
                String str;
                if (!(str = br.readLine()).equals("Predicates start")) {
                    javax.swing.JOptionPane.showMessageDialog(null, "Неверный формат файла");
                    fr.close();
                    return;
                }
                PredlistModel.clear();
                predicates.clear();
                str = br.readLine();
                while (str != null && !str.equals("Predicates end")) {
                    //загрузка предикатов
                    String name = str;
                    ImageIcon image = new ImageIcon();
                    if (str.equals("См. рисунок")) {
                        String path = chooser.getSelectedFile().getPath();
                        if (path.contains("\\")) {    //windows
                            System.out.println("WINDOWS");
                            path = path.substring(0, path.lastIndexOf('\\') + 1);

                            String filename = chooser.getSelectedFile().getName().substring(0, chooser.getSelectedFile().getName().indexOf(".eo"));
                            image = new ImageIcon(path + filename + predicates.size() + ".jpg");
                        }
                        if (path.contains("/")) {  //unix
                            System.out.println("UNIX");
                            path = path.substring(0, path.lastIndexOf('/') + 1);

                            String filename = chooser.getSelectedFile().getName().substring(0, chooser.getSelectedFile().getName().indexOf(".eo"));
                            image = new ImageIcon(path + filename + predicates.size() + ".jpg");
                        }
                    } else {
                        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympApp.class);
                        image = resourceMap.getImageIcon("NoImage.icon");
                    }

                    predicates.add(new Predicate(name, image));
                    PredlistModel.addElement((char) ('A' + PredlistModel.getSize()) + " = " + str);
                    str = br.readLine();
                }
                if (!str.equals("Predicates end")) {
                    javax.swing.JOptionPane.showMessageDialog(null, "Неверный формат файла");
                    fr.close();
                    return;
                }

                if (!(str = br.readLine()).equals("Table start")) {
                    javax.swing.JOptionPane.showMessageDialog(null, "Неверный формат файла");
                    fr.close();
                    return;
                }
                TableMod = new MyDefaultTableModel();
                TablePred.setModel(TableMod);

                TableMod.addColumn("");
                for (int i = 0; i < PredlistModel.size(); i++)
                    TableMod.addColumn((char) ('A' + i));

                str = br.readLine();
                while (str != null && !str.equals("Table end")) {
                    //загрузка строк таблицы
                    Vector<String> c = new Vector();
                    c.add((char) ('A' + TableMod.getRowCount()) + "");
                    for (int i = 0; i < str.length(); i++)
                        c.add(str.charAt(i) + "");
                    TableMod.addRow(c);
                    str = br.readLine();
                }
                if (!str.equals("Table end")) {
                    javax.swing.JOptionPane.showMessageDialog(null, "Неверный формат файла");
                    fr.close();
                    return;
                }

                setColumnNoEdit(TablePred, 0);
                org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympApp.class);
                jLabel1.setIcon(resourceMap.getImageIcon("NoImageIcon.icon"));

                //Потеря выделения таблицы. Убираем кнопки
                EditTableText.setEnabled(false);
                Plus.setEnabled(false);
                Minus.setEnabled(false);
                Question.setEnabled(false);
                Sharp.setEnabled(false);
                ClearTable.setEnabled(false);

                fr.close();
                javax.swing.JOptionPane.showMessageDialog(null, "Файл успешно загружен");
            }
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            return;
        } catch (NumberFormatException e) {
            System.out.println("Number Format Exception");
            return;
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }

    @Action
    public void newfile() {
        predicates.clear();
        PredlistModel.clear();
        TableMod = new MyDefaultTableModel();
        TablePred.setModel(TableMod);

        PredEdit.setEditable(false);
        PredEdit.setEnabled(false);
        PredEdit.setText("");
        ChangePred.setEnabled(false);
        DelPred.setEnabled(false);
        SaveEditPred.setEnabled(false);
        CancelEditPred.setEnabled(false);
        EditPredText.setEnabled(false);
        NewPred.setText("Введите предикат");
        EditTableText.setEnabled(false);
        Plus.setEnabled(false);
        Minus.setEnabled(false);
        Question.setEnabled(false);
        Sharp.setEnabled(false);
        ClearTable.setEnabled(false);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.ipo.dces.editors.expressolymp.ExpressOlympApp.class).getContext().getResourceMap(ExpressOlympApp.class);
        jLabel1.setIcon(resourceMap.getImageIcon("NoImageIcon.icon"));
    }

    @Action
    public void generateTask() {
        int countPred = 5;
        int mainPred = -1;
        int imageSize = 200;
        Vector<Integer> sPred = new Vector();

        try {
            //check
            if (TablePred.getRowCount() < 6) {
                javax.swing.JOptionPane.showMessageDialog(null, "Для успешной генерации тестов число предикатов должно быть не меньше 6");
                return;
            }
            for (int j = 0; j < TablePred.getRowCount(); j++)
                for (int i = 1; i < TablePred.getColumnCount(); i++) {
                    if (TableMod.getValueAt(j, i) == null || TableMod.getValueAt(j, i).toString().equals("")) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Незаполненное поле [" + (char) ('A' + j) + " ," + (char) ('A' + i - 1) + "]");
                        return;
                    }
                    if (!(TableMod.getValueAt(j, i).toString().equals("+") || TableMod.getValueAt(j, i).toString().equals("-") || TableMod.getValueAt(j, i).toString().equals("?") || TableMod.getValueAt(j, i).toString().equals("#"))) {
                        javax.swing.JOptionPane.showMessageDialog(null, "Недопустимое значение в поле [" + (char) ('A' + j) + " ," + (char) ('A' + i - 1) + "]");
                        return;
                    }
                }

            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new File("."));
            ExtFileFilter textFileFilter = new ExtFileFilter("problem", "Задания экспресс-олимпиады (*.problem)");
            //Отключение вывода расширения в строке описания, так как расширение уже задано в строке описания
            textFileFilter.setExtensionListInDescription(false);
            chooser.addChoosableFileFilter(textFileFilter);


            if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                String path = chooser.getSelectedFile().getPath();
                String fname = chooser.getSelectedFile().getName();
                String extpr = ".problem";
                Boolean isWin = true;
                if (fname.endsWith(extpr))
                    fname = fname.substring(0, fname.lastIndexOf(extpr));

                if (path.contains("\\")) {    //windows
                    System.out.println("WINDOWS");
                    isWin = true;
                    path = path.substring(0, path.lastIndexOf('\\') + 1);
                }
                if (path.contains("/")) {  //unix
                    System.out.println("UNIX");
                    isWin = false;
                    path = path.substring(0, path.lastIndexOf('/') + 1);
                }
                if (isWin)
                    path += "problem\\";
                else
                    path += "problem/";

                new File(path).mkdir();
                Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + fname + ".eo"), "UTF8"));
                Writer fwman = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "MANIFEST"), "UTF8"));
                fwman.write("﻿<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
                fwman.write("<resources>");
                fwman.write("    <alias path=\"statement\" target=\"" + fname + ".eo\"/>");
                fwman.write("    <contents path=\"statement~type\">text/html</contents>");
                fwman.write("    <contents path=\"right answer\">");

                fw.write("<HTML>");
                fw.write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
                fw.write("<BODY>");
                fw.write("<b><p>");
                fw.write("Известно, что ");

                Random r = new Random();
                mainPred = r.nextInt(predicates.size());
                if (predicates.get(mainPred).name.equals("См. рисунок")) {
                    Image img = predicates.get(mainPred).image.getImage();
                    BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2 = bi.createGraphics();
                    g2.drawImage(img, 0, 0, null);
                    g2.dispose();
                    ImageIO.write(bi, "jpg", new File(path + fname + "MP.jpg"));

                    fw.write("<img src=\"" + fname + "MP.jpg\" width=\"" + imageSize + "\" height=\"" + imageSize + "\">");
                } else
                    fw.write(predicates.elementAt(mainPred).name);

                fw.write(".</p>");
                fw.write("<p>");
                fw.write("Оцените следующие высказывания: ");
                fw.write("</p></b>");

                boolean err = false;
                for (int i = 0, j = 0; i < countPred && j < 100; i++, j++) {
                    int q = r.nextInt(predicates.size());
                    if (sPred.contains(q) || TableMod.getValueAt(mainPred, q + 1).toString().equals("#"))
                        i--;
                    else {
                        fw.write("<p>" + (i + 1) + ". ");
                        sPred.add(q);

                        if (predicates.get(q).name.equals("См. рисунок")) {
                            Image img = predicates.get(q).image.getImage();
                            BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
                            Graphics2D g2 = bi.createGraphics();
                            g2.drawImage(img, 0, 0, null);
                            g2.dispose();
                            ImageIO.write(bi, "jpg", new File(path + fname + q + ".jpg"));

                            fw.write("<img src='" + fname + q + ".jpg' width=\"" + imageSize + "\" height=\"" + imageSize + "\">");
                        } else
                            fw.write(predicates.elementAt(q).name);
                        fw.write("</p>");

                        fwman.write(TableMod.getValueAt(mainPred, q + 1).toString());
                    }

                    if (j == 99)
                        err = true;

                }

                if (err)
                    javax.swing.JOptionPane.showMessageDialog(null, "Ошибка генерации задания. Попробуйте еще раз");

                fwman.write("</contents>\n");
                fwman.write("    <contents path=\"client plugin\">ExpressOlympPlugin</contents>\n");
                fwman.write("    <contents path=\"server plugin\">ExpressOlympChecker</contents>\n");
                fwman.write("    <teacher path=\"answer\"/>\n");
                fwman.write("    <teacher path=\"right answer\"/>>\n");
                fwman.write("</resources>\n");
                fwman.close();

                fw.write("</BODY>");
                fw.write("</HTML>");
                fw.close();

                //Создадим задачу. Это будет zip файл
                ZipUtils.zip(
                        new File("problem"), //архивируемый каталог
                        new File(fname + ".problem") //файл, куда сохраняется архив
                );


                deleteDir(new File(path));
                javax.swing.JOptionPane.showMessageDialog(null, "Файл успешно сохранен");
            }
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            return;
        } catch (NumberFormatException e) {
            System.out.println("Number Format Exception");
            return;
        } catch (Exception e) {
            System.out.println(e);
            return;
        }
    }

    public void deleteDir(File file) {
        if (!file.exists())
            return;
        if (file.isDirectory()) {
            for (File f : file.listFiles())
                deleteDir(f);
            file.delete();
        } else
            file.delete();
    }

}